﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Collections.Specialized;

namespace SimpleUnitity.Config
{
    public class SimpleUnitityConfigSection : ConfigurationSection
    {
        [ConfigurationProperty("filename", IsRequired = true)]
        public string Filename
        {
            get { return (string)base["filename"]; }
            set { base["filename"] = value; }
        }

        [ConfigurationProperty("enable", IsRequired = false, DefaultValue = "true")]
        public string Enable
        {
            get { return (string)base["enable"]; }
            set { base["enable"] = value; }
        }

        public bool IsEnable
        {
            get { return Convert.ToBoolean(Enable); }
        }

        readonly object syncObject = new object();

        private NameValueCollection appSettings;
        public NameValueCollection AppSettings
        {
            get
            {
                if (appSettings == null)
                {
                    lock (syncObject)
                    {
                        if (syncObject == null)
                        {
                            appSettings = new NameValueCollection();
                            if (IsEnable)
                            {
                                var config = ConfigurationManager.OpenExeConfiguration(Filename);
                                foreach (var item in config.AppSettings.Settings.AllKeys)
                                {
                                    appSettings.Add(item, config.AppSettings.Settings[item].Value);
                                }
                            }
                        }
                    }
                }
                return appSettings;
            }
        }

        public ConnectionStringSettingsCollection ConnectionStrings
        {
            get
            {
                if (IsEnable == false)
                {
                    return new ConnectionStringSettingsCollection();
                }
                else
                {
                    var config = ConfigurationManager.OpenExeConfiguration(Filename);
                    return config.ConnectionStrings.ConnectionStrings;
                }
            }
        }

        public ConfigurationSection GetSection(string sectionName)
        {
            return IsEnable ? ConfigurationManager.OpenExeConfiguration(Filename).GetSection(sectionName) : null;
        }

        public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName)
        {
            return IsEnable ? ConfigurationManager.OpenExeConfiguration(Filename).GetSectionGroup(sectionGroupName) : null;
        }
    }
}
